<?php

		class Users extends CI_Controller {
				
				function __construct(){
						parent::__construct();
				}
				
				function index(){
						die('index');						
				}
				
				function pull_accts_v2(){
						$ids = array('66668635');
						//print_r($ids);
						$user = new User();
						foreach($ids as $mt4_uid){
								$user->clear();
								$user->where('mt4_uid',(int)$mt4_uid)->get(1);
								$data = $this->_mt4_info($mt4_uid);
								if(is_array($data) && isset($data['login']))
								{
										$type = 'real';
										if(strtolower($data['group'])=='gm-auto') 			$type = 'real';
										elseif(strtolower($data['group'])=='gm-fix-mini') 	$type = 'real';
										elseif(strtolower($data['group'])=='demoforex') 	$type = 'demo';
										
										if(!$user->exists())
										{
												$this->load->library('encrypt');
												$user->lang 			= 'en';
												$user->type 			= $type;
												$user->title 			= '';
												$user->firstname 		= $data['name'];
												$user->lastname 		= '';
												$user->country 			= $data['country'];
												$user->email 			= $data['email'];
												$user->password 		= $this->encrypt->encode('12345678');
												$user->phone 			= '';
												$user->phone2 			= '';
												$user->address1 		= $data['adress'];
												$user->address2 		= '';
												$user->city 			= $data['city'];
												$user->state 			= '';
												$user->zip 				= $data['zip'];
												$user->citizenship 		= '';
												$user->nid 				= '';
												$user->dob_day 			= '';
												$user->dob_month 		= '';
												$user->dob_year 		= '';
												$user->dob_ts 			= '';
												$user->business 		= '';
												$user->exp_securities 	= '';
												$user->exp_currencies 	= '';
												$user->exp_futures 		= '';
												$user->exp_commodities 	= '';
												$user->primary_acct  	= 'no';
												$user->balance  		= $data['balance'];
												$user->free_margin  	= $data['free_margin'];
												$user->mt4_uid 			= $data['login'];
												if(isset($data['agent']) && $data['agent']) $user->mt4_agent = $data['agent'];
												if(isset($data['group']) && $data['group']) $user->mt4_group = $data['group'];
												$user->added 			= $data['regdate'];
												$user->user_ip 			= '';
												$user->u_stat 			= 'active';
												$user->save();
												
												echo "<span style=\"color:blue;\">{$data['name']}</span> [#".$this->db->insert_id()."]";
										}
										else
										{
												$record = array(
														'zip'=>$data['zip'],
														'balance'=>$data['balance'],
														'free_margin'=>$data['free_margin']
												);
												
												if(isset($data['agent']) && $data['agent']) $record['mt4_agent'] = $data['agent'];
												if(isset($data['group']) && $data['group']) $record['mt4_group'] = $data['group'];
												
												$user->where('mt4_uid',(int)$mt4_uid)
													 ->update($record);
												echo "<span style=\"color:#ff0000;\">{$data['name']}</span>";
										}
										echo "<br />\n";
								}
						}
						die();
				}
				
				function pull_accts_v3(){
						$file = './mt4-ids.csv';
						if(!is_file($file))
						{
								die("<strong>$file</strong> does not exist!");
						}
						$lines = file($file,FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES);
						//print_r($lines);
						$user = new User();
						foreach($lines as $line){
								$items = explode(';', $line);
								if(!preg_match('#[0-9]+#is', @$items[0])) continue;
								$mt4_uid = $items[0];
								// echo "$mt4_uid<br />";
								// continue;
								
								$user->clear();
								$user->where('mt4_uid',(int)$mt4_uid)->get(1);
								$data = $this->_mt4_info($mt4_uid);
								if(is_array($data) && isset($data['login']))
								{
										$type = '';
										if(strtolower($data['group'])=='ecm-auto') 			$type = 'real';
										elseif(strtolower($data['group'])=='ecm-fix-mini') 	$type = 'real';
										elseif(strtolower($data['group'])=='demoecm') 	    $type = 'demo';
										
										if(!$user->exists())
										{
												$this->load->library('encrypt');
												$user->lang 			= 'en';
												$user->type 			= $type;
												$user->title 			= '';
												$user->firstname 		= $data['name'];
												$user->lastname 		= '';
												$user->country 			= $data['country'];
												$user->email 			= $data['email'];
												$user->password 		= $this->encrypt->encode('P9eT5a');
												$user->phone 			= '';
												$user->phone2 			= '';
												$user->address1 		= $data['adress'];
												$user->address2 		= '';
												$user->city 			= $data['city'];
												$user->state 			= '';
												$user->zip 				= $data['zip'];
												$user->citizenship 		= '';
												$user->nid 				= '';
												$user->dob_day 			= '';
												$user->dob_month 		= '';
												$user->dob_year 		= '';
												$user->dob_ts 			= '';
												$user->business 		= '';
												$user->exp_securities 	= '';
												$user->exp_currencies 	= '';
												$user->exp_futures 		= '';
												$user->exp_commodities 	= '';
												$user->primary_acct  	= 'no';
												$user->balance  		= $data['balance'];
												$user->free_margin  	= $data['free_margin'];
												$user->mt4_uid 			= $data['login'];
												if(isset($data['agent']) && $data['agent']) $user->mt4_agent = $data['agent'];
												if(isset($data['group']) && $data['group']) $user->mt4_group = $data['group'];
												$user->added 			= $data['regdate'];
												$user->user_ip 			= '';
												$user->u_stat 			= 'active';
												$user->save();
												
												echo "<span style=\"color:blue;\">$mt4_uid -> {$data['name']}</span> [#".$this->db->insert_id()."]";
										}
										else
										{
												$record = array(
														'zip'=>$data['zip'],
														'balance'=>$data['balance'],
														'free_margin'=>$data['free_margin']
												);
												
												if(isset($data['agent']) && $data['agent']) $record['mt4_agent'] = $data['agent'];
												if(isset($data['group']) && $data['group']) $record['mt4_group'] = $data['group'];
												
												$user->where('mt4_uid',(int)$mt4_uid)
													 ->update($record);
												echo "<span style=\"color:#ff0000;\">$mt4_uid -> {$data['name']}</span>";
										}
										echo "<br />\n";
								}
						}
						die();
				}
				
				function pull_accts(){
						$file = './mt4-id.csv';
						if(!is_file($file))
						{
								die("<strong>$file</strong> does not exist!");
						}
						$ids = file($file,FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES);
						//print_r($ids);
						$user = new User();
						foreach($ids as $mt4_uid){
								$user->clear();
								$user->where('mt4_uid',(int)$mt4_uid)->get(1);
								$data = $this->_mt4_info($mt4_uid);
								if(is_array($data) && isset($data['login']))
								{
										$type = '';
										if(strtolower($data['group'])=='ecm-auto') 			$type = 'real';
										elseif(strtolower($data['group'])=='ecm-fix-mini') 	$type = 'real';
										elseif(strtolower($data['group'])=='demoecm') 	$type = 'demo';
										
										if(!$user->exists())
										{
												$this->load->library('encrypt');
												$user->lang 			= 'en';
												$user->type 			= $type;
												$user->title 			= '';
												$user->firstname 		= $data['name'];
												$user->lastname 		= '';
												$user->country 			= $data['country'];
												$user->email 			= $data['email'];
												$user->password 		= $this->encrypt->encode('12345678');
												$user->phone 			= '';
												$user->phone2 			= '';
												$user->address1 		= $data['adress'];
												$user->address2 		= '';
												$user->city 			= $data['city'];
												$user->state 			= '';
												$user->zip 				= $data['zip'];
												$user->citizenship 		= '';
												$user->nid 				= '';
												$user->dob_day 			= '';
												$user->dob_month 		= '';
												$user->dob_year 		= '';
												$user->dob_ts 			= '';
												$user->business 		= '';
												$user->exp_securities 	= '';
												$user->exp_currencies 	= '';
												$user->exp_futures 		= '';
												$user->exp_commodities 	= '';
												$user->primary_acct  	= 'no';
												$user->balance  		= $data['balance'];
												$user->free_margin  	= $data['free_margin'];
												$user->mt4_uid 			= $data['login'];
												if(isset($data['agent']) && $data['agent']) $user->mt4_agent = $data['agent'];
												if(isset($data['group']) && $data['group']) $user->mt4_group = $data['group'];
												$user->added 			= $data['regdate'];
												$user->user_ip 			= '';
												$user->u_stat 			= 'active';
												$user->save();
												
												echo "<span style=\"color:blue;\">{$data['name']}</span> [#".$this->db->insert_id()."]";
										}
										else
										{
												$record = array(
														'zip'=>$data['zip'],
														'balance'=>$data['balance'],
														'free_margin'=>$data['free_margin']
												);
												
												if(isset($data['agent']) && $data['agent']) $record['mt4_agent'] = $data['agent'];
												if(isset($data['group']) && $data['group']) $record['mt4_group'] = $data['group'];
												
												$user->where('mt4_uid',(int)$mt4_uid)
													 ->update($record);
												echo "<span style=\"color:#ff0000;\">{$data['name']}</span>";
										}
										echo "<br />\n";
								}
						}
						die();
				}
				
				function _mt4_info($mt4_uid){
						$this->load->library('cmt4datareceiver');
						
						$opts = read_options('mt4_host,mt4_port', 'OBJECT');
						
						$host 		= $opts->mt4_host;
						$port 		= (int)$opts->mt4_port;

						try {
								$chk = $this->cmt4datareceiver->OpenConnection($host, $port);
								if($chk===0) {
										$params 		 = array();
										$params['login'] = $mt4_uid;
										$data 	 		= $this->cmt4datareceiver->MakeRequest("getaccountinfo", $params);
										$this->cmt4datareceiver->CloseConnection();
										return $data;
								}
								else
								{
										return false;
								}
						} catch(Exception $e) {
								return false;
						}
						return false;		
				}
				
				function _import_users(){
						$file = './users_data.csv';
						if(!is_file($file))
						{
								die("<strong>$file</strong> does not exist!");
						}
						$lines = file($file,FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES);
						$user = new User();
						$this->load->library('encrypt');
						for($i=0;$i<count($lines);$i++)
						{
								$items = explode(';',$lines[$i]);
								if($items[0]=='Language' && $items[1]=='Type') continue;
								
								$user->clear();
								$user->lang 			= strtolower($items[0]);
								$user->type 			= strtolower($items[1]);
								$user->title 			= '';
								$user->firstname 		= $items[3];
								$user->lastname 		= $items[4];
								$user->country 			= $items[5];
								$user->email 			= $items[6];
								$user->password 		= $this->encrypt->encode($items[16]);
								$user->phone 			= $items[8];
								$user->phone2 			= $items[9];
								$user->address1 		= $items[10];
								$user->address2 		= $items[11];
								$user->city 			= $items[12];
								$user->state 			= $items[13];
								$user->citizenship 		= $items[15];
								$user->nid 				= '';
								$user->dob_day 			= '';
								$user->dob_month 		= '';
								$user->dob_year 		= '';
								$user->dob_ts 			= '';
								$user->business 		= '';
								$user->exp_securities 	= '';
								$user->exp_currencies 	= '';
								$user->exp_futures 		= '';
								$user->exp_commodities 	= '';
								$user->primary_acct  	= 'yes';
								$user->mt4_uid 			= $items[18];
								$user->added 			= time();
								$user->user_ip 			= '';
								$user->u_stat 			= "active"; 
								//$user->save();
								//$user_id 				= $this->db->insert_id();
								
								//echo "<strong>#$user_id</strong> added<br />";
						}
						die();
				}
				
				function __import_users(){
						$file = './account-import.csv';
						if(!is_file($file))
						{
								die("<strong>$file</strong> does not exist!");
						}
						$lines = file($file,FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES);
						$user = new User();
						$this->load->library('encrypt');
						for($i=0;$i<count($lines);$i++)
						{
								$items = explode(';',$lines[$i]);
								if($items[0]=='Login') continue;
								echo "#$i. {$items[0]}<br />";
								
								$user->clear();
								$user->where('mt4_uid',$items[0])->get(1);
								if($user->exists()) continue;
								$info = $this->_mt4_info($items[0]);
								// print_r($info);
								// print_r($items);
								// die("Line #$i: $lines[$i]");
								
								if(strtolower(substr($items[3],0,7))=='gm-auto') 	$type = 'real';
								elseif(strtolower($items[3])=='gm-fix-mini') 		$type = 'real';
								elseif(strtolower($items[3])=='demoforex') 			$type = 'demo';
								else												$type = 'real';
								
								$user->clear();
								$user->lang 			= 'en';
								$user->type 			= $type;
								$user->title 			= '';
								$user->firstname 		= $items[2];
								$user->lastname 		= '';
								$user->country 			= $items[4];
								$user->email 			= $items[10];
								$user->password 		= $this->encrypt->encode($items[1]);
								$user->phone 			= $items[9];
								$user->phone2 			= '';
								$user->address1 		= $items[8];
								$user->address2 		= '';
								$user->city 			= $items[5];
								$user->state 			= $items[6];
								$user->zip 				= $items[7];
								$user->citizenship 		= '';
								$user->nid 				= '';
								$user->dob_day 			= '';
								$user->dob_month 		= '';
								$user->dob_year 		= '';
								$user->dob_ts 			= '';
								$user->business 		= '';
								$user->exp_securities 	= '';
								$user->exp_currencies 	= '';
								$user->exp_futures 		= '';
								$user->exp_commodities 	= '';
								$user->primary_acct  	= 'yes';
								$user->mt4_uid 			= $items[0];
								$user->mirror_login_id	= '';
								$user->mt4_group 		= $items[3];
								$user->mt4_agent 		= @$info['agent'];
								$user->leverage 		= @$info['leverage'];
								$user->primary_acct 	= 'no';
								$user->first_login 		= 'no';
								$user->verify 			= 'no';
								$user->balance 			= @$info['balance'];
								$user->free_margin 		= @$info['free_margin'];
								$user->credit 			= $items[18];
								$user->added 			= @$info['regdate'];
								$user->user_ip 			= '';
								$user->u_stat 			= "active"; 
								$user->save();
								$user_id 				= $this->db->insert_id();
								echo "<strong>#$user_id</strong> added<br />";
						}
						die('Finished');
				}
				
				function _resolve_lang(){
						$langs = array('en','fr');
						$lang  = '';
						for($i=3;$i<$this->uri->total_segments();$i++)
						{
								if($this->uri->segment($i)=='lang' && $this->uri->segment($i+1) && in_array($this->uri->segment($i+1),$langs))
								{
										$lang = $this->uri->segment($i+1);
										break;
								}
						}
						if(!$lang && $this->session->userdata('sess_lang'))
						{
								$lang = $this->session->userdata('sess_lang');
						}
						if( !in_array($lang,$langs) ) $lang = $langs[0];
						if($lang) $this->session->set_userdata('sess_lang', $lang);
						return $lang;
				}
				
				function register_live(){
						$lang = $this->_resolve_lang();
						
						$this->lang->load('users_register_live', $lang);
						$data['ref'] 			= $this->_resolve_referrer();
						$data['base_url'] 		= base_url();
						$localized_errors		= array (
								'error_field_required' => $this->lang->line('error_field_required'),
								'error_password_match' => $this->lang->line('error_password_match'),
						);
						$data['locale'] 							= array('lang'=>$lang, 'errors'=>$localized_errors, 'msg_loading'=>$this->lang->line('msg_loading').'...', 'msg_processing'=>$this->lang->line('label_processing'),'select_choose'=>$this->lang->line('select_choose').'...');
						$data['locale']['label_dob_month']			= $this->lang->line('label_dob_month');
						$data['locale']['label_dob_day']			= $this->lang->line('label_dob_day');
						$data['locale']['label_dob_year']			= $this->lang->line('label_dob_year');
						$data['locale']['months_list']				= $this->lang->line('months_list');
						$data['locale']['securities_exp_list']		= $this->lang->line('securities_exp_list');
						$data['locale']['currencies_exp_list']		= $this->lang->line('currencies_exp_list');
						$data['locale']['futures_exp_list']			= $this->lang->line('futures_exp_list');
						$data['locale']['commodities_exp_list']		= $this->lang->line('commodities_exp_list');
						
						$opts = read_options('company_name', 'OBJECT');
						
						$data['company_name'] 	= $opts->company_name;
						$this->load->view('users/register_live', $data);
				}
				
				function register_lsuccess(){	
						
						$user_id = $this->uri->segment(3);
						if(!$user_id)
						{
								redirect( base_url() . 'users/register_live/' );
						}
						
						$user = new User();
						$user->where('id',(int)$user_id)->get(1);
						if(!$user->exists())
						{
								redirect( base_url() . 'users/register_live/' );
						}
						
						$opts = read_options('company_name', 'OBJECT');
						
						$lang = $this->_resolve_lang();
						$this->lang->load('users_register_live', $lang);
						$data['base_url'] = base_url();
						$data['user'] = $user;
						$data['company_name'] 	= $opts->company_name;
						$this->load->view('users/register_live_success', $data);
				}
				
				function register_dsuccess(){	
						
						$user_id = $this->uri->segment(3);
						if(!$user_id)
						{
								redirect( base_url() . 'users/register_demo/' );
						}
						
						$user = new User();
						$user->where('id',(int)$user_id)->get(1);
						if(!$user->exists())
						{
								redirect( base_url() . 'users/register_demo/' );
						}
						
						$opts = read_options('company_name', 'OBJECT');
						
						$lang = $this->_resolve_lang();
						$this->lang->load('users_register_demo', $lang);
						$data['base_url'] = base_url();
						$data['user'] = $user;
						$data['company_name'] 	= $opts->company_name;
						$this->load->view('users/register_demo_success', $data);
				}
				
				function _resolve_referrer(){
						$this->load->helper('cookie');
						$ref = 0;
						for($i=3;$i<$this->uri->total_segments();$i++)
						{
								if( $this->uri->segment($i)=='ref' && $this->uri->segment($i+1) )
								{
										$ref = (int)$this->uri->segment($i);
										break;
								}
						}
						if($ref>0)
						{
								$referer = new User();
								$referer->where('id',(int)$ref)->get(1);
								if( $referer->exists() )
								{
										$opts = read_options('', 'OBJECT');
										$uri = parse_url(base_url());
										$this->load->library('encrypt');
										$cookie = array(
											'name'   => '__rid',
											'value'  => $this->encrypt->encode($ref),
											'expire' => $aff_ttl->exists()?$opts->aff_ttl:2678400,
											'domain' => '.'.@$uri['host'],
											'path'   => '/'
										);
										$this->input->set_cookie($cookie); 
										return $ref;
								}
						}
						elseif($this->input->cookie('__rid'))
						{
								$ref = (int)$this->encrypt->decode($this->input->cookie('__rid'));
						}
						return $ref;
				}
				
				function ajax_register_live(){
						$langs	= array('en','fr');
						$lang 	= $this->input->post('lang') && in_array($this->input->post('lang'),$langs) ? $this->input->post('lang') : $langs[0];
						
						if( $this->input->is_ajax_request() ) {
								$this->_validate_live_signup();
								
								$country_name 	= '';
								$user_title 	= '';
								$primary_acct   = 'yes';
								$dmp = $this->config->item('datamapper');
								
								$title = new User_title();
								$title->where('id',(int)$this->input->post('title'))->get(1);
								if($title->exists()) {
										if($title->lang==$langs[0])
										{
												$user_title = $title->title;
										}
										else
										{
												$rel_title = new User_title();
												$rel_title->where('lang',$langs[0])->where('id',$title->rel_id)->get(1);
												if($rel_title->exists()) $user_title = $rel_title->title;
										}
								}
								
								$country = new Country();
								$country->where('id',(int)$this->input->post('country'))->get(1);
								if($country->exists()) {
										if($country->lang==$langs[0])
										{
												$country_name = $country->name_short;
										}
										else
										{
												$rel_country = new Country();
												$rel_country->where('lang',$langs[0])->where('iso_num',$country->iso_num)->get(1);
												if($rel_country->exists()) $country_name = $rel_country->name_short;
										}
								}
								
								$mt4_agent  = '';
								$ref 		= $this->input->post('ref') ? $this->input->post('ref') : $this->_resolve_referrer();
								$referrer 	= new User();
								if($ref>0)  {
										$referrer->where('id',(int)$ref)->get(1);
										if($referrer->exists())
										{
												$mt4_agent = $referrer->mt4_uid;
										}
								}
								else
								{
										$user_tree = new User();
										$user_tree->where('email',$this->security->xss_clean($this->input->post('email')))->order_by('id','asc')->get();
										foreach($user_tree as $rel_user)
										{
												if($rel_user->mt4_agent)
												{
														$mt4_agent 		= $rel_user->mt4_agent;
														$primary_acct   = 'no';
														break;
												}
										}
								}
								
								$this->load->library('encrypt');
								
								$explicit_referral 		= $this->_fetch_explicit_referral();
								
								# Save user info in database
								
								$tu   = new User();  	$tu->where('email',$this->security->xss_clean($this->input->post('email')))->get(1);
								$user = new User();
								$user->lang 			= $lang;
								$user->type 			= 'real';
								$user->title 			= is_numeric($user_title) ? $this->_fetch_user_title_by_id($user_title) : $user->title;
								$user->firstname 		= $this->input->post('firstname');
								$user->lastname 		= $this->input->post('lastname');
								$user->country 			= is_numeric($country_name) ? $this->_fetch_country_by_id($country_name) : $country_name;
								$user->email 			= $this->input->post('email');
								$user->password 		= $this->encrypt->encode($this->input->post('password'));
								$user->phone 			= $this->input->post('phone');
								$user->phone2 			= $this->input->post('phone2');
								$user->address1 		= $this->input->post('address1');
								$user->address2 		= $this->input->post('address2');
								$user->city 			= $this->input->post('city');
								$user->state 			= $this->input->post('state');
								$user->zip 				= $this->input->post('zip');
								$user->citizenship 		= $this->input->post('citizenship');
								$user->nid 				= $this->input->post('nid');
								$user->dob_day 			= $this->input->post('dob_day');
								$user->dob_month 		= $this->input->post('dob_month');
								$user->dob_year 		= $this->input->post('dob_year');
								$user->dob_ts 			= mktime(0,0,0,$user->dob_month,$user->dob_day,$user->dob_year);
								$user->business 		= $this->input->post('business');
								$user->exp_securities 	= $this->input->post('exp_securities');
								$user->exp_currencies 	= $this->input->post('exp_currencies');
								$user->exp_futures 		= $this->input->post('exp_futures');
								$user->exp_commodities 	= $this->input->post('exp_commodities');
								$user->mirror_request 	= $this->input->post('mirror_request');
								$user->primary_acct  	= $tu->exists()?'no':'yes';
								$user->first_login  	= 'yes';
								$user->referral  		= $explicit_referral;
								$user->u_added 			= time();
								$user->user_ip 			= $this->input->ip_address();
								$user->u_stat 			= 'active';
								$user->save();
								$user_id 				= $this->db->insert_id();
								log_activity('Account #' . $user_id . ' (signup): user info successfully saved in database. E-mail: ' . $user->email, 'user', 'live_signup', 'system');
											
								# prepare request to MT4 server			
								$opts 							= read_options('mt4_host,mt4_port,default_leverage,default_group,default_agent', 'OBJECT');								
								$params 						= array();
								$params['state'] 				= $user->state;
								$params['email'] 				= $user->email;
								$params['group'] 				= $opts->default_group;
								$params['city'] 				= $user->city;
								$params['password_investor'] 	= '0';
								$params['leverage'] 		 	= $opts->default_leverage;
								$params['id'] 					= '';
								$params['address'] 				= $user->address1 . ($user->address2 ? ' ' . $user->address2 : '');
								$params['country'] 				= $user->country;
								$params['password'] 			= $this->input->post('password');
								$params['password_phone'] 		= '';
								$params['name'] 				= $user->firstname . ($user->firstname&&$user->lastname?' ':'') . $user->lastname;
								$params['zipcode'] 				= $user->zip;
								$params['phone'] 				= $this->input->post('phone');
								$params['login'] 				= 0;
								$params['comment'] 				= "real #$user_id";
								$params['agent'] 				= $explicit_referral&&is_numeric($explicit_referral) ? $explicit_referral : ($mt4_agent ? $mt4_agent : $opts->default_agent);
								
								$this->load->library('mt4');
								
								# 5 connection attemps to MT4 server
								$connected = false;
								for($i=0;$i<3;$i++)
								{
										if($this->mt4->connect($opts->mt4_host, (int)$opts->mt4_port)!==FALSE)
										{
												$connected = true;
												break;
										}
										sleep(1);
								}
								if(!$connected) // Connection failed. Rollback...
								{
										if($user_id>0) $this->db->delete(@$dmp['prefix'] . 'users', array('id' => (int)$user_id)); 
										log_activity('Account #' . $user_id . ' (signup): Connection to server failed (Reason: '.$this->mt4->errstr.'). User record removed from database.', 'user', 'live_signup', 'system');
										die(json_encode(array('error'=>$this->mt4->errstr)));
								}
								
								# 'createaccount' request to MT4 server
								$resp = $this->mt4->request("createaccount", $params);
								if($resp===FALSE) 			
								{
										if($user_id>0) $this->db->delete(@$dmp['prefix'] . 'users', array('id' => (int)$user_id)); 
										log_activity('Account #' . $user_id . ' (signup): MT4 \'createaccount\' request failed (Reason: '.$this->mt4->errstr.'). User record removed from database.', 'user', 'live_signup', 'system');
										die(json_encode(array('error'=>$this->mt4->errstr)));
								}
								
								if(!isset($resp['result'])) die(json_encode(array('error'=>'Internal Error.')));
								if($resp['result']<0) 		
								{
										if($user_id>0) $this->db->delete(@$dmp['prefix'] . 'users', array('id' => (int)$user_id)); 
										log_activity('Account #' . $user_id . ' (signup): MT4 \'createaccount\' request failed (Reason: '.@$resp['reason'].'). User record removed from database.', 'user', 'live_signup', 'system');
										die(json_encode(array('error'=>'Error: ' . @$resp['reason'])));
								}
								
								# Update user MT4 ID
								if(@$resp['login']>0)
								{
										$user->clear();
										$user->where('id', $user_id)->update(array('mt4_uid'=>$resp['login'], 'u_updated'=>time()));
										log_activity('Account #' . $user_id . ' (signup): MT4 Account successfully created. MT4 ID: ' . $resp['login'] . '.', 'user', 'live_signup', 'system');
								}
								
								# Get account info from MT4 server and update agent and group
								$ACK 			 = false;
								$params 		 = array();
								$params['login'] = @$resp['login'];
								for($i=0;$i<3;$i++)
								{
										$accountInfo = $this->mt4->request("getaccountinfo", $params);
										if(isset($accountInfo['group']) && isset($accountInfo['agent']))
										{
												$user->clear();
												$user->where('id', $user_id)->update( array('mt4_group'=>$accountInfo['group'], 'mt4_agent'=>@$accountInfo['agent'], 'u_updated'=>time()) );
												$ACK = true;
												break;
										}
										sleep(1);
								}
								if(!$ACK)
								{
										log_activity('Account #' . $user_id . ' (signup): Could not retrieve MT4 agent and group for this user.', 'user', 'live_signup', 'system');
								}
								
								$this->_alert_live_signup($lang, $user_id);
								if($this->input->post('mirror_request')=='yes')
								{
										$user->clear();
										$user->where('id', $user_id)->get(1);
										
										$subject = '#' . $user->mt4_uid.' '.$user->firstname.($user->firstname && $user->lastname?' ':'').$user->lastname.' requested for Mirror Account';
										$message = 'MT4 ID: ' . $user->mt4_uid;
										
										$this->load->library('email');
										$opts 					= read_options('smtp_ssl,smtp_host,smtp_user,smtp_pass,smtp_port,company_name,admin_email', 'OBJECT');
										$config['protocol'] 	= 'smtp';
										$config['smtp_host'] 	= ($opts->smtp_ssl=='yes' && substr(strtolower($opts->smtp_host), 0, 6)!='ssl://' ? 'ssl://' : '') . $opts->smtp_host;
										$config['smtp_user'] 	= $opts->smtp_user;
										$config['smtp_pass'] 	= $opts->smtp_pass;
										$config['smtp_port'] 	= $opts->smtp_port;
										$config['mailtype'] 	= 'html';
										$config['charset'] 		= 'utf-8';
										$this->email->initialize($config);
										$this->email->set_newline("\r\n");
										
										$this->email->from($opts->smtp_user, $opts->company_name);
										$this->email->to($opts->admin_email);
										$this->email->subject($subject);
										$this->email->message($message);
										$this->email->send();
										$data = $this->email->print_debugger();
										if(preg_match('#Your message has been successfully sent#is', $data))
										{
												log_activity('Account #' . $user_id . ' (signup): Partner request e-mail successfully sent to '.$opts->admin_email, 'user', 'live_signup', 'system');
										}
										else
										{
												log_activity('Account #' . $user_id . ' (signup): Failure sending Partner request e-mail to '.$opts->admin_email, 'user', 'live_signup', 'system');
										}
								}	
								$this->mt4->disconnect();
								log_activity('Account #' . $user_id . ' (signup): Disconnected from MT4 server.', 'user', 'live_signup', 'system');
								die( json_encode(array('success'=>true, 'user_id'=>$user_id)) );
						}
						die(json_encode(array('error'=>'Malformed request.')));
				}
				
				function _alert_live_signup($lang, $user_id){
						$opts = read_options('', 'OBJECT');
						
						$tpl_email = new Tpl_email(); $tpl_email->where('type','signup_live_conf')->get(1);
						$user = new User(); $user->where('id',(int)$user_id)->get(1);
						
						if($tpl_email->exists() && $user->exists())
						{
								$subject = $this->_map_client_presets($user_id, $tpl_email->subject);
								$subject = $this->_map_option_presets($subject);
								$message = $this->_map_client_presets($user_id, $tpl_email->message);
								$message = $this->_map_option_presets($message);
								// die($subject);
								// die($message);
								
								$this->load->library('email');
								$config['protocol'] 	= 'smtp';
								$config['smtp_host'] 	= ($opts->smtp_ssl=='yes' && substr(strtolower($opts->smtp_host), 0, 6)!='ssl://' ? 'ssl://' : '') . $opts->smtp_host;
								$config['smtp_user'] 	= $opts->smtp_user;
								$config['smtp_pass'] 	= $opts->smtp_pass;
								$config['smtp_port'] 	= $opts->smtp_port;
								$config['mailtype'] 	= 'html';
								$config['charset'] 		= 'utf-8';
								$this->email->initialize($config);
								$this->email->set_newline("\r\n");
								
								$this->email->from($opts->smtp_user, $opts->company_name);
								$this->email->to($user->email);
								$this->email->subject($subject);
								$this->email->message($message);
								$this->email->send();
								$data = $this->email->print_debugger();
								// if($fp = fopen('./live-email-log-txt', 'wa+'))
								// {
										// fputs($fp, $data);
										// fclose($fp);
								// }
								if(preg_match('#Your message has been successfully sent#is', $data))
								{
										log_activity('Live Signup e-mail successfully sent to '.$user->email, 'user', 'live_signup', 'system');
								}
								else
								{
										log_activity('Failure sending Live Signup e-mail to '.$user->email, 'user', 'live_signup', 'system');
								}
						}
				}
				
				function register_live_2(){
						$lang = $this->_resolve_lang();
						
						$this->lang->load('users_register_aim', $lang);
						$data['ref'] 			= $this->_resolve_referrer();
						$data['base_url'] 		= base_url();
						$localized_errors		= array (
								'error_field_required' => $this->lang->line('error_field_required'),
								'error_password_match' => $this->lang->line('error_password_match'),
						);
						$data['locale'] 							= array('lang'=>$lang, 'errors'=>$localized_errors, 'msg_loading'=>$this->lang->line('msg_loading').'...', 'msg_processing'=>$this->lang->line('label_processing'),'select_choose'=>$this->lang->line('select_choose').'...');
						$data['locale']['label_dob_month']			= $this->lang->line('label_dob_month');
						$data['locale']['label_dob_day']			= $this->lang->line('label_dob_day');
						$data['locale']['label_dob_year']			= $this->lang->line('label_dob_year');
						$data['locale']['months_list']				= $this->lang->line('months_list');
						$data['locale']['securities_exp_list']		= $this->lang->line('securities_exp_list');
						$data['locale']['currencies_exp_list']		= $this->lang->line('currencies_exp_list');
						$data['locale']['futures_exp_list']			= $this->lang->line('futures_exp_list');
						$data['locale']['commodities_exp_list']		= $this->lang->line('commodities_exp_list');
						
						$opts = read_options('company_name', 'OBJECT');
						
						$data['company_name'] 	= $opts->company_name;
						$this->load->view('users/register_aim', $data);
				}
				
				function ajax_register_aim(){
						$langs	= array('en','fr');
						$lang 	= $this->input->post('lang') && in_array($this->input->post('lang'),$langs) ? $this->input->post('lang') : $langs[0];
						
						if( $this->input->is_ajax_request() ) {
								$this->_validate_aim_signup();
								
								$country_name 	= '';
								$user_title 	= '';
								$primary_acct   = 'yes';
								$dmp = $this->config->item('datamapper');
								
								$title = new User_title();
								$title->where('id',(int)$this->input->post('title'))->get(1);
								if($title->exists()) {
										if($title->lang==$langs[0])
										{
												$user_title = $title->title;
										}
										else
										{
												$rel_title = new User_title();
												$rel_title->where('lang',$langs[0])->where('id',$title->rel_id)->get(1);
												if($rel_title->exists()) $user_title = $rel_title->title;
										}
								}
								
								$country = new Country();
								$country->where('id',(int)$this->input->post('country'))->get(1);
								if($country->exists()) {
										if($country->lang==$langs[0])
										{
												$country_name = $country->name_short;
										}
										else
										{
												$rel_country = new Country();
												$rel_country->where('lang',$langs[0])->where('iso_num',$country->iso_num)->get(1);
												if($rel_country->exists()) $country_name = $rel_country->name_short;
										}
								}
								
								$mt4_agent  = '';
								$ref 		= $this->input->post('ref') ? $this->input->post('ref') : $this->_resolve_referrer();
								$referrer 	= new User();
								if($ref>0)  {
										$referrer->where('id',(int)$ref)->get(1);
										if($referrer->exists())
										{
												$mt4_agent = $referrer->mt4_uid;
										}
								}
								else
								{
										$user_tree = new User();
										$user_tree->where('email',$this->security->xss_clean($this->input->post('email')))->order_by('id','asc')->get();
										foreach($user_tree as $rel_user)
										{
												if($rel_user->mt4_agent)
												{
														$mt4_agent 		= $rel_user->mt4_agent;
														$primary_acct   = 'no';
														break;
												}
										}
								}
								
								$this->load->library('encrypt');
								
								$explicit_referral 		= $this->_fetch_explicit_referral();
								
								# Save user info in database
								$tu   = new User();  	$tu->where('email',$this->security->xss_clean($this->input->post('email')))->get(1);
								$user = new User();
								$user->lang 			= $lang;
								$user->type 			= 'aim';
								$user->title 			= is_numeric($user_title) ? $this->_fetch_user_title_by_id($user_title) : $user->title;
								$user->firstname 		= $this->input->post('firstname');
								$user->lastname 		= $this->input->post('lastname');
								$user->country 			= is_numeric($country_name) ? $this->_fetch_country_by_id($country_name) : $country_name;
								$user->email 			= $this->input->post('email');
								$user->password 		= $this->encrypt->encode($this->input->post('password'));
								$user->phone 			= $this->input->post('phone');
								$user->phone2 			= $this->input->post('phone2');
								$user->address1 		= $this->input->post('address1');
								$user->address2 		= $this->input->post('address2');
								$user->city 			= $this->input->post('city');
								$user->state 			= $this->input->post('state');
								$user->zip 				= $this->input->post('zip');
								$user->citizenship 		= $this->input->post('citizenship');
								$user->nid 				= $this->input->post('nid');
								$user->dob_day 			= $this->input->post('dob_day');
								$user->dob_month 		= $this->input->post('dob_month');
								$user->dob_year 		= $this->input->post('dob_year');
								$user->dob_ts 			= mktime(0,0,0,$user->dob_month,$user->dob_day,$user->dob_year);
								$user->business 		= $this->input->post('business');
								$user->exp_securities 	= $this->input->post('exp_securities');
								$user->exp_currencies 	= $this->input->post('exp_currencies');
								$user->exp_futures 		= $this->input->post('exp_futures');
								$user->exp_commodities 	= $this->input->post('exp_commodities');
								$user->mirror_request 	= $this->input->post('mirror_request');
								$user->primary_acct  	= $tu->exists()?'no':'yes';
								$user->first_login  	= 'yes';
								$user->referral  		= $explicit_referral;
								$user->u_added 			= time();
								$user->user_ip 			= $this->input->ip_address();
								$user->u_stat 			= 'active';
								$user->save();
								$user_id 				= $this->db->insert_id();
								log_activity('Account #' . $user_id . ' (signup): user info successfully saved in database. E-mail: ' . $user->email, 'user', 'aim_signup', 'system');
											
								# prepare request to MT4 server			
								$opts 							= read_options('mt4_host,mt4_port,aim_leverage,aim_group,default_agent,aim_alert_client,aim_alert_admin', 'OBJECT');								
								$params 						= array();
								$params['state'] 				= $user->state;
								$params['email'] 				= $user->email;
								$params['group'] 				= $opts->aim_group;
								$params['city'] 				= $user->city;
								$params['password_investor'] 	= '0';
								$params['leverage'] 		 	= $opts->aim_leverage;
								$params['id'] 					= '';
								$params['address'] 				= $user->address1 . ($user->address2 ? ' ' . $user->address2 : '');
								$params['country'] 				= $user->country;
								$params['password'] 			= $this->input->post('password');
								$params['password_phone'] 		= '';
								$params['name'] 				= $user->firstname . ($user->firstname&&$user->lastname?' ':'') . $user->lastname;
								$params['zipcode'] 				= $user->zip;
								$params['phone'] 				= $this->input->post('phone');
								$params['login'] 				= 0;
								$params['comment'] 				= "aim #$user_id";
								$params['agent'] 				= $explicit_referral && is_numeric($explicit_referral) ? $explicit_referral : ($mt4_agent ? $mt4_agent : $opts->default_agent);
								
								$this->load->library('mt4');
								
								# 5 connection attemps to MT4 server
								$connected = false;
								for($i=0;$i<3;$i++)
								{
										if($this->mt4->connect($opts->mt4_host, (int)$opts->mt4_port)!==FALSE)
										{
												$connected = true;
												break;
										}
										sleep(1);
								}
								if(!$connected) // Connection failed. Rollback...
								{
										if($user_id>0) $this->db->delete(@$dmp['prefix'] . 'users', array('id' => (int)$user_id)); 
										log_activity('Account #' . $user_id . ' (signup): Connection to server failed (Reason: '.$this->mt4->errstr.'). User record removed from database.', 'user', 'aim_signup', 'system');
										die(json_encode(array('error'=>$this->mt4->errstr)));
								}
								
								# 'createaccount' request to MT4 server
								$resp = $this->mt4->request("createaccount", $params);
								if($resp===FALSE) 			
								{
										if($user_id>0) $this->db->delete(@$dmp['prefix'] . 'users', array('id' => (int)$user_id)); 
										log_activity('Account #' . $user_id . ' (signup): MT4 \'createaccount\' request failed (Reason: '.$this->mt4->errstr.'). User record removed from database.', 'user', 'aim_signup', 'system');
										die(json_encode(array('error'=>$this->mt4->errstr)));
								}
								
								if(!isset($resp['result'])) die(json_encode(array('error'=>'Internal Error.')));
								if($resp['result']<0) 		
								{
										if($user_id>0) $this->db->delete(@$dmp['prefix'] . 'users', array('id' => (int)$user_id)); 
										log_activity('Account #' . $user_id . ' (signup): MT4 \'createaccount\' request failed (Reason: '.@$resp['reason'].'). User record removed from database.', 'user', 'aim_signup', 'system');
										die(json_encode(array('error'=>'Error: ' . @$resp['reason'])));
								}
								
								# Update user MT4 ID
								if(@$resp['login']>0)
								{
										$user->clear();
										$user->where('id', $user_id)->update(array('mt4_uid'=>$resp['login'], 'u_updated'=>time()));
										log_activity('Account #' . $user_id . ' (signup): MT4 Account successfully created. MT4 ID: ' . $resp['login'] . '.', 'user', 'aim_signup', 'system');
								}
								
								# Get account info from MT4 server and update agent and group
								$ACK 			 = false;
								$params 		 = array();
								$params['login'] = @$resp['login'];
								for($i=0;$i<3;$i++)
								{
										$accountInfo = $this->mt4->request("getaccountinfo", $params);
										if(isset($accountInfo['group']) && isset($accountInfo['agent']))
										{
												$user->clear();
												$user->where('id', $user_id)->update( array('mt4_group'=>$accountInfo['group'], 'mt4_agent'=>@$accountInfo['agent'], 'u_updated'=>time()) );
												$ACK = true;
												break;
										}
										sleep(1);
								}
								if(!$ACK)
								{
										log_activity('Account #' . $user_id . ' (signup): Could not retrieve MT4 agent and group for this user.', 'user', 'aim_signup', 'system');
								}
								
								if(@$opts->aim_alert_client=='yes')
								{
										$this->_alert_aim_signup($lang, $user_id);
								}
								if(@$opts->aim_alert_admin=='yes')
								{
										$this->_alert_aim_admin($lang, $user_id);
								}
								
								$this->mt4->disconnect();
								log_activity('Account #' . $user_id . ' (signup): Disconnected from MT4 server.', 'user', 'aim_signup', 'system');
								die( json_encode(array('success'=>true, 'user_id'=>$user_id)) );
						}
						die(json_encode(array('error'=>'Malformed request.')));
				}
				
				function _validate_aim_signup(){
						$lang = $this->_resolve_lang();
						$this->lang->load('users_register_aim', $lang);
						$user = new User();
						$user->where('email',$this->input->post('email'))->where('email !=','')->get(1);
						
						if( !$this->input->post('title') ) {
								die( json_encode(array('field_id'=>'title','error'=>$this->lang->line('error_field_required'))) );
						} elseif( !$this->input->post('firstname') ) {
								die( json_encode(array('field_id'=>'firstname','error'=>$this->lang->line('error_field_required'))) );
						} elseif( !$this->input->post('lastname') ) {
								die( json_encode(array('field_id'=>'lastname','error'=>$this->lang->line('error_field_required'))) );
						} elseif( !$this->input->post('country') ) {
								die( json_encode(array('field_id'=>'country','error'=>$this->lang->line('error_field_required'))) );
						} elseif( !$this->input->post('email') ) {
								die( json_encode(array('field_id'=>'email','error'=>$this->lang->line('error_field_required'))) );
						} elseif( !$this->input->post('password') ) {
								die( json_encode(array('field_id'=>'password','error'=>$this->lang->line('error_field_required'))) );
						} elseif( !$this->input->post('phone') ) {
								die( json_encode(array('field_id'=>'phone','error'=>$this->lang->line('error_field_required'))) );
						} elseif( !$this->input->post('address1') ) {
								die( json_encode(array('field_id'=>'firstname','error'=>$this->lang->line('error_field_required'))) );
						} elseif( !$this->input->post('city') ) {
								die( json_encode(array('field_id'=>'city','error'=>$this->lang->line('error_field_required'))) );
						} elseif( !$this->input->post('state') ) {
								die( json_encode(array('field_id'=>'state','error'=>$this->lang->line('error_field_required'))) );
						} elseif( !$this->input->post('citizenship') ) {
								die( json_encode(array('field_id'=>'citizenship','error'=>$this->lang->line('error_field_required'))) );
						} elseif( !$this->input->post('nid') ) {
								die( json_encode(array('field_id'=>'nid','error'=>$this->lang->line('error_field_required'))) );
						} elseif( !$this->input->post('dob_day') ) {
								die( json_encode(array('field_id'=>'dob_day','error'=>$this->lang->line('error_field_required'))) );
						} elseif( !$this->input->post('dob_month') ) {
								die( json_encode(array('field_id'=>'dob_month','error'=>$this->lang->line('error_field_required'))) );
						} elseif( !$this->input->post('dob_year') ) {
								die( json_encode(array('field_id'=>'dob_year','error'=>$this->lang->line('error_field_required'))) );
						}
						
						return TRUE;
				}
				
				function _alert_aim_signup($lang, $user_id){
						$opts = read_options('', 'OBJECT');
						
						$tpl_email = new Tpl_email(); $tpl_email->where('type','signup_aim_conf')->get(1);
						$user = new User(); $user->where('id',(int)$user_id)->get(1);
						
						if($tpl_email->exists() && $user->exists())
						{
								$subject = $this->_map_client_presets($user_id, $tpl_email->subject);
								$subject = $this->_map_option_presets($subject);
								$message = $this->_map_client_presets($user_id, $tpl_email->message);
								$message = $this->_map_option_presets($message);
								
								$this->load->library('email');
								$config['protocol'] 	= 'smtp';
								$config['smtp_host'] 	= ($opts->smtp_ssl=='yes' && substr(strtolower($opts->smtp_host), 0, 6)!='ssl://' ? 'ssl://' : '') . $opts->smtp_host;
								$config['smtp_user'] 	= $opts->smtp_user;
								$config['smtp_pass'] 	= $opts->smtp_pass;
								$config['smtp_port'] 	= $opts->smtp_port;
								$config['mailtype'] 	= 'html';
								$config['charset'] 		= 'utf-8';
								$this->email->initialize($config);
								$this->email->set_newline("\r\n");
								
								$this->email->from($opts->smtp_user, $opts->company_name);
								$this->email->to($user->email);
								$this->email->subject($subject);
								$this->email->message($message);
								$this->email->send();
								$data = $this->email->print_debugger();
								if(preg_match('#Your message has been successfully sent#is', $data))
								{
										log_activity('AIM Signup e-mail successfully sent to '.$user->email, 'user', 'aim_signup', 'system');
								}
								else
								{
										log_activity('Failure sending AIM Signup e-mail to '.$user->email, 'user', 'aim_signup', 'system');
								}
						}
				}
				
				function _alert_aim_admin($lang, $user_id) {
						$opts = read_options('', 'OBJECT');
						
						$user = new User(); 
						$user->where('id',(int)$user_id)->get(1);
						
						if($user->exists())
						{
								$this->load->library('encrypt');
								
								$subject = '#' . $user->mt4_uid . ' ' . $user->firstname.($user->firstname&&$user->lastname?' ':'').$user->lastname.' have just sign up for AIM, Awaiting Approval.';
								$message = "
Pending Partner Informations:
---
Title: 					".$user->title."
First Name: 			".$user->firstname."
Last Name: 				".$user->lastname."
Country: 				".$user->country_name."
E-mail: 				".$user->email."
Password: 				".$this->encrypt->decode($user->password)."
Phone: 					".$user->phone."
Phone2: 				".$user->phone2."
Address line 1: 		".$user->address1."
Address line 2:			".$user->address2."
City: 					".$user->city."
State: 					".$user->state."
Citizenship: 			".$user->citizenship."
Passport ID: 			".$user->nid."
Date of birth: 			".$user->dob_month."/".$user->dob_day."/".$user->dob_year."
Business: 				".$user->business."
Experience in forex: 	".$user->exp_forex."
Monthly customers:		".$user->customers_monthly."
Total accounts: 		".$user->total_accts."
Total clients' funds: 	".$user->total_clients_funds."
Broker relation: 		".$user->broker_relation."
Website: 				".$user->website."
Promo_material: 	 	".$user->promo_material."
Promo_method: 	 		".$user->promo_method."
Other_info: 		 	".$user->other_info."

IP Address: 			".$this->input->ip_address()."
---
";

								$this->load->library('email');
								$config['protocol'] 	= 'smtp';
								$config['smtp_host'] 	= ($opts->smtp_ssl=='yes'&& substr(strtolower($opts->smtp_host), 0, 6)!='ssl://' ? 'ssl://' : '') . $opts->smtp_host;
								$config['smtp_user'] 	= $opts->smtp_user;
								$config['smtp_pass'] 	= $opts->smtp_pass;
								$config['smtp_port'] 	= $opts->smtp_port;
								$config['mailtype'] 	= 'html';
								$config['charset'] 		= 'utf-8';
								$config['wordwrap']  	= TRUE;
								$this->email->initialize($config);
								$this->email->set_newline("\r\n");
								
								$this->email->from($opts->smtp_user, $opts->company_name);
								$this->email->to($opts->admin_email);
								$this->email->subject($subject);
								$this->email->message(nl2br($message));
								$this->email->send();
								$data = $this->email->print_debugger();
								if(preg_match('#Your message has been successfully sent#is', $data))
								{
										log_activity('AIM Signup notice successfully sent to '.$opts->admin_email, 'user', 'aim_signup', 'system');
								}
								else
								{
										log_activity('Failure sending AIM Signup notice to '.$opts->admin_email, 'user', 'aim_signup', 'system');
								}
						}
				}
				
				function register_asuccess(){	
						
						$user_id = $this->uri->segment(3);
						if(!$user_id)
						{
								redirect( base_url() . 'users/register_live_2/' );
						}
						
						$user = new User();
						$user->where('id',(int)$user_id)->get(1);
						if(!$user->exists())
						{
								redirect( base_url() . 'users/register_live_2/' );
						}
						
						$opts = read_options('company_name', 'OBJECT');
						
						$lang = $this->_resolve_lang();
						$this->lang->load('users_register_aim', $lang);
						$data['base_url'] = base_url();
						$data['user'] = $user;
						$data['company_name'] 	= $opts->company_name;
						$this->load->view('users/register_aim_success', $data);
				}
				
				
				function _map_option_presets($str) {
						$opts = read_options('', 'OBJECT');
						$find = array(
							'{admin_email}',
							'{company_name}',
							'{logo}',
						);
						$replaceby = array(
							$opts->admin_email,
							$opts->company_name,
							'<img src="'.$opts->logo.'"'.($opts->logo_width?' width="'.$opts->logo_width.'"':'').($opts->logo_height?' height="'.$opts->logo_height.'"':'').'>',
						);
						return str_replace($find,$replaceby,$str);
				}
				
				function _map_client_presets($user_id, $str) {
						$user = new User();
						$user->where('id',(int)$user_id)->get(1);
						$find = array(
								'{client_id}', 
								'{client_name}', 
								'{client_first_name}', 
								'{client_last_name}', 
								'{client_country}', 
								'{client_email}', 
								'{client_password}', 
								'{client_phonenumber}', 
								'{client_address1}', 
								'{client_address2}', 
								'{client_city}', 
								'{client_state}', 
								'{client_company}', 
								'{client_postcode}', 
								'{client_mt4_id}', 
								'{client_mirror_login}', 
								'{client_group}', 
								'{client_mt4_agent}', 
								'{client_leverage}', 
								'{client_stored_doc}', 
								'{client_signature_image}'
						);
						$replaceby = array(
								$user->id,
								$user->firstname . ($user->firstname&&$user->lastname?' ':'') . $user->lastname,
								$user->firstname,
								$user->lastname,
								$user->country,
								$user->email,
								$this->encrypt->decode($user->password),
								$user->phone,
								$user->address1,
								$user->address2,
								$user->city,
								$user->state,
								$user->business,
								$user->zip,
								$user->mt4_uid,
								$user->mirror_login_id,
								$user->mt4_group,
								$user->mt4_agent,
								$user->leverage,
								$user->stored_doc ? base_url().'data/'.$user->id.'/'.$user->stored_doc : '',
								$user->signature_image_200x122 ? '<img src="'.base_url().'data/'.$user->id.'/'.$user->signature_image_200x122.'" />' : ''
						);
						return str_replace($find,$replaceby,$str);
				}
				
				function _validate_live_signup(){
						$lang = $this->_resolve_lang();
						$this->lang->load('users_register_live', $lang);
						$user = new User();
						$user->where('email',$this->input->post('email'))->where('email !=','')->get(1);
						
						if( !$this->input->post('title') ) {
								die( json_encode(array('field_id'=>'title','error'=>$this->lang->line('error_field_required'))) );
						} elseif( !$this->input->post('firstname') ) {
								die( json_encode(array('field_id'=>'firstname','error'=>$this->lang->line('error_field_required'))) );
						} elseif( !$this->input->post('lastname') ) {
								die( json_encode(array('field_id'=>'lastname','error'=>$this->lang->line('error_field_required'))) );
						} elseif( !$this->input->post('country') ) {
								die( json_encode(array('field_id'=>'country','error'=>$this->lang->line('error_field_required'))) );
						} elseif( !$this->input->post('email') ) {
								die( json_encode(array('field_id'=>'email','error'=>$this->lang->line('error_field_required'))) );
						} elseif( !$this->input->post('password') ) {
								die( json_encode(array('field_id'=>'password','error'=>$this->lang->line('error_field_required'))) );
						} elseif( !$this->input->post('phone') ) {
								die( json_encode(array('field_id'=>'phone','error'=>$this->lang->line('error_field_required'))) );
						} elseif( !$this->input->post('address1') ) {
								die( json_encode(array('field_id'=>'firstname','error'=>$this->lang->line('error_field_required'))) );
						} elseif( !$this->input->post('city') ) {
								die( json_encode(array('field_id'=>'city','error'=>$this->lang->line('error_field_required'))) );
						} elseif( !$this->input->post('state') ) {
								die( json_encode(array('field_id'=>'state','error'=>$this->lang->line('error_field_required'))) );
						} elseif( !$this->input->post('citizenship') ) {
								die( json_encode(array('field_id'=>'citizenship','error'=>$this->lang->line('error_field_required'))) );
						} elseif( !$this->input->post('nid') ) {
								die( json_encode(array('field_id'=>'nid','error'=>$this->lang->line('error_field_required'))) );
						} elseif( !$this->input->post('dob_day') ) {
								die( json_encode(array('field_id'=>'dob_day','error'=>$this->lang->line('error_field_required'))) );
						} elseif( !$this->input->post('dob_month') ) {
								die( json_encode(array('field_id'=>'dob_month','error'=>$this->lang->line('error_field_required'))) );
						} elseif( !$this->input->post('dob_year') ) {
								die( json_encode(array('field_id'=>'dob_year','error'=>$this->lang->line('error_field_required'))) );
						}
						
						return TRUE;
				}
		
				function register_demo(){
						$lang = $this->_resolve_lang();
						
						$this->lang->load('users_register_demo', $lang);
						$data['base_url'] 		= base_url();
						$localized_errors		= array (
								'error_field_required' => $this->lang->line('error_field_required'),
								'error_password_match' => $this->lang->line('error_password_match'),
						);
						$data['locale'] 		= array('lang'=>$lang, 'errors'=>$localized_errors, 'msg_loading'=>$this->lang->line('msg_loading').'...', 'msg_processing'=>$this->lang->line('label_processing'),'select_choose'=>$this->lang->line('select_choose').'...');
						$opts = read_options('company_name', 'OBJECT');
						$data['company_name'] 	= $opts->company_name;
						$data['ref'] 			= $this->_resolve_referrer();
						$this->load->view('users/register_demo', $data);
				}
				
				function ajax_register_demo(){
						$langs	= array('en','fr');
						$lang 	= $this->input->post('lang') && in_array($this->input->post('lang'),$langs) ? $this->input->post('lang') : $langs[0];
						
						if( $this->input->is_ajax_request() ) {
								$this->_validate_demo_signup();
								
								$country_name 	= '';
								$user_title 	= '';
								$dmp 			= $this->config->item('datamapper');
								
								$title = new User_title();
								$title->where('id',(int)$this->input->post('title'))->get(1);
								if($title->exists())
								{
										if($title->lang==$langs[0])
										{
												$user_title = $title->title;
										}
										else
										{
												$rel_title = new User_title();
												$rel_title->where('lang',$langs[0])->where('id',$title->rel_id)->get(1);
												if($rel_title->exists()) $user_title = $rel_title->title;
										}
								}
								
								$country = new Country();
								$country->where('id',(int)$this->input->post('country'))->get(1);
								if($country->exists())
								{
										if($country->lang==$langs[0])
										{
												$country_name = $country->name_short;
										}
										else
										{
												$rel_country = new Country();
												$rel_country->where('lang',$langs[0])->where('iso_num',$country->iso_num)->get(1);
												if($rel_country->exists()) $country_name = $rel_country->name_short;
										}
								}
								
								$mt4_agent  = '';
								$ref 		= $this->input->post('ref') ? $this->input->post('ref') : $this->_resolve_referrer();
								$referrer 	= new User();
								if($ref>0) 
								{
										$referrer->where('id',(int)$ref)->get(1);
										if($referrer->exists())
										{
												$mt4_agent = $referrer->mt4_uid;
										}
								}
								else
								{
										$user_tree = new User();
										$user_tree->where('email',$this->security->xss_clean($this->input->post('email')))->order_by('id','asc')->get();
										foreach($user_tree as $rel_user)
										{
												if($rel_user->mt4_agent)
												{
														$mt4_agent = $rel_user->mt4_agent;
														break;
												}
										}
								}
								
								$this->load->library('encrypt');
								
								$explicit_referral 				= $this->_fetch_explicit_referral();
								
								# Save user info in database
								$tu   = new User();  	$tu->where('email',$this->security->xss_clean($this->input->post('email')))->get(1);
								$user = new User();
								$user->lang 			= $lang;
								$user->type 			= 'demo';
								$user->title 			= $user_title;
								$user->firstname 		= $this->input->post('firstname');
								$user->lastname 		= $this->input->post('lastname');
								$user->country 			= $country->exists() ? $country->country : '';
								$user->email 			= $this->input->post('email');
								$user->password 		= $this->encrypt->encode($this->input->post('password'));
								$user->phone 			= $this->input->post('phone');
								$user->primary_acct  	= $tu->exists()?'no':'yes';
								$user->first_login  	= 'yes';
								$user->referral  		= $explicit_referral;
								$user->added 			= time();
								$user->user_ip 			= $this->input->ip_address();
								$user->u_stat 			= "active";
								$user->save();
								$user_id 				= $this->db->insert_id();
								log_activity('Account #' . $user_id . ' (signup): user info successfully saved in database. E-mail: ' . $user->email, 'user', 'demo_signup', 'system');
								
								# prepare request to MT4 server			
								$opts 							= read_options('mt4_host,mt4_port,demo_leverage,default_demo_group,default_agent', 'OBJECT');								
								$params 						= array();
								$params['state'] 				= $user->state;
								$params['email'] 				= $user->email;
								$params['group'] 				= $opts->default_demo_group;
								$params['city'] 				= $user->city;
								$params['password_investor'] 	= '0';
								$params['leverage'] 		 	= $opts->demo_leverage;
								$params['id'] 					= '';
								$params['address'] 				= $user->address1 . ($user->address2 ? ' ' . $user->address2 : '');
								$params['country'] 				= $user->country;
								$params['password'] 			= $this->input->post('password');
								$params['password_phone'] 		= '';
								$params['name'] 				= $user->firstname . ($user->firstname&&$user->lastname?' ':'') . $user->lastname;
								$params['zipcode'] 				= '';
								$params['phone'] 				= $this->input->post('phone');
								$params['login'] 				= 0;
								$params['comment'] 				= "demo #$user_id";
								$params['agent'] 				= $explicit_referral && is_numeric($explicit_referral) ? $explicit_referral : ($mt4_agent ? $mt4_agent : $opts->default_agent);
								
								$this->load->library('mt4');
								$mt4_uid = 0;
								
								# 5 connection attemps to MT4 server
								$connected = false;
								for($i=0;$i<3;$i++)
								{
										if($this->mt4->connect($opts->mt4_host, (int)$opts->mt4_port)!==FALSE)
										{
												$connected = true;
												break;
										}
										sleep(1);
								}
								if(!$connected) // Connection failed. Rollback...
								{
										if($user_id>0) $this->db->delete(@$dmp['prefix'] . 'users', array('id' => (int)$user_id)); 
										log_activity('Account #' . $user_id . ' (signup): Connection to server failed (Reason: '.$this->mt4->errstr.'). User record removed from database.', 'user', 'demo_signup', 'system');
										die(json_encode(array('error'=>$this->mt4->errstr)));
								}
								
								# 'createaccount' request to MT4 server
								$resp = $this->mt4->request("createaccount", $params);
								if($resp===FALSE) 			
								{
										if($user_id>0) $this->db->delete(@$dmp['prefix'] . 'users', array('id' => (int)$user_id)); 
										log_activity('Account #' . $user_id . ' (signup): MT4 \'createaccount\' request failed (Reason: '.$this->mt4->errstr.'). User record removed from database.', 'user', 'demo_signup', 'system');
										die(json_encode(array('error'=>$this->mt4->errstr)));
								}
								
								if(!isset($resp['result'])) die(json_encode(array('error'=>'Internal Error.')));
								if($resp['result']<0) 		
								{
										if($user_id>0) $this->db->delete(@$dmp['prefix'] . 'users', array('id' => (int)$user_id)); 
										log_activity('Account #' . $user_id . ' (signup): MT4 \'createaccount\' request failed (Reason: '.@$resp['reason'].'). User record removed from database.', 'user', 'demo_signup', 'system');
										die(json_encode(array('error'=>'Error: ' . @$resp['reason'])));
								}
								
								# Update user MT4 ID
								if(@$resp['login']>0)
								{
										$user->clear();
										$user->where('id', $user_id)->update(array('mt4_uid'=>$resp['login'], 'u_updated'=>time()));
										log_activity('Account #' . $user_id . ' (signup): MT4 Account successfully created. MT4 ID: ' . $resp['login'] . '.', 'user', 'demo_signup', 'system');
										
										$mt4_uid 			= $resp['login'];
										$params['login'] 	= $mt4_uid;
										$params['value'] 	= 100000.00;
										$params['comment'] 	= 'Demo account deposit';
										$ret 				= $this->mt4->request('changebalance', $params);
										if($ret['result']<0) 		
										{
												log_activity('Account #' . $user_id . ' (signup): MT4 \'changebalance\' request failed (Reason: '.@$ret['reason'].').', 'user', 'demo_signup', 'system');
										}
										else
										{
												$user->clear();
												$user->where('id', $user_id)->update(array('balance'=>100000.00, 'u_updated'=>time()));
												log_activity('Account #' . $user_id . ' (signup): Account balance updated to 100000.00', 'user', 'demo_signup', 'system');
										}
								}
								
								# Get account info from MT4 server and update agent and group
								$ACK 			 = false;
								$params 		 = array();
								$params['login'] = @$resp['login'];
								for($i=0;$i<3;$i++)
								{
										$accountInfo = $this->mt4->request("getaccountinfo", $params);
										if(isset($accountInfo['group']) && isset($accountInfo['agent']))
										{
												$user->clear();
												$user->where('id', $user_id)->update( array('mt4_group'=>$accountInfo['group'], 'mt4_agent'=>@$accountInfo['agent'], 'u_updated'=>time()) );
												$ACK = true;
												break;
										}
										sleep(1);
								}
								if(!$ACK)
								{
										log_activity('Account #' . $user_id . ' (signup): Could not retrieve MT4 agent and group for this user.', 'user', 'demo_signup', 'system');
								}
								
								$this->_alert_demo_signup($lang, $user_id);
									
								$this->mt4->disconnect();
								log_activity('Account #' . $user_id . ' (signup): Disconnected from MT4 server.', 'user', 'demo_signup', 'system');
								die( json_encode(array('success'=>true, 'user_id'=>$user_id)) );
						}						
				}
				
				function _fetch_explicit_referral(){
						$referral = trim($this->input->post('referral'));
						if($referral)
						{
								$user = new User();
								if(preg_match('#^[0-9]+$#', $referral))
								{
										$user->where('mt4_uid', (int)$referral)->get(1);
										if($user->exists()) return $user->mt4_uid;
										$user->clear();
										
										$user->where('id', (int)$referral)->get(1);
										if($user->exists()) return $user->mt4_uid;
								}
								$user->clear();
								$user->where('email', $this->security->xss_clean($referral))->order_by('id', 'asc')->get(1);
								if($user->exists()) return $user->mt4_uid;
						}
						return $referral;
				}
				
				function get_symbols(){
						$this->load->library('cmt4datareceiver');
						//$params['login'] 	= "$mt4_uid";
						$opts = read_options('mt4_host,mt4_port', 'OBJECT');
						try {
							$chk = $this->cmt4datareceiver->OpenConnection($opts->mt4_host, $opts->mt4_port);
							$answerData = $this->cmt4datareceiver->MakeRequest("getsymbols");
							print_r($answerData);
						} catch(Exception $logOrIgnore) {}
				}
				
				function _change_account_balance($mt4_uid, $balance){
						$this->load->library('cmt4datareceiver');
						$params['login'] 	= "$mt4_uid";
						$params['value'] 	= (double)$balance;
						$params['comment'] 	= "demo account deposit";
						$opts = read_options('mt4_host,mt4_port', 'OBJECT');
						$port->where('name','mt4_port')->get(1);
						try {
							$chk = $this->cmt4datareceiver->OpenConnection($opts->mt4_host, $opts->mt4_port);
							$answerData = $this->cmt4datareceiver->MakeRequest("changebalance", $params);
							return $answerData;
						} catch(Exception $logOrIgnore) {}
				}
				
				function _get_account_balance($mt4_uid){
						$this->load->library('cmt4datareceiver');
						$params['login'] 	= "$mt4_uid";
						$opts = read_options('mt4_host,mt4_port', 'OBJECT');
						try {
							$chk = $this->cmt4datareceiver->OpenConnection($opts->mt4_host, $opts->mt4_port);
							$answerData = $this->cmt4datareceiver->MakeRequest("getaccountbalance", $params);
							return $answerData;
						} catch(Exception $logOrIgnore) {}
				}
				
				function _validate_demo_signup(){
						$lang = $this->_resolve_lang();
						$this->lang->load('users_register_demo', $lang);
						$user = new User();
						$user->where('email',$this->input->post('email'))->where('email !=','')->get(1);
						
						if( !$this->input->post('title') ) {
								die( json_encode(array('stat'=>'error','field_id'=>'title','msg'=>$this->lang->line('error_field_required'))) );
						} elseif( !$this->input->post('firstname') ) {
								die( json_encode(array('stat'=>'error','field_id'=>'firstname','msg'=>$this->lang->line('error_field_required'))) );
						} elseif( !$this->input->post('lastname') ) {
								die( json_encode(array('stat'=>'error','field_id'=>'lastname','msg'=>$this->lang->line('error_field_required'))) );
						} elseif( !$this->input->post('country') ) {
								die( json_encode(array('stat'=>'error','field_id'=>'country','msg'=>$this->lang->line('error_field_required'))) );
						} elseif( !$this->input->post('email') ) {
								die( json_encode(array('stat'=>'error','field_id'=>'email','msg'=>$this->lang->line('error_field_required'))) );
						} elseif( !$this->input->post('password') ) {
								die( json_encode(array('stat'=>'error','field_id'=>'password','msg'=>$this->lang->line('error_field_required'))) );
						} elseif( !$this->input->post('phone') ) {
								die( json_encode(array('stat'=>'error','field_id'=>'phone','msg'=>$this->lang->line('error_field_required'))) );
						}
						return TRUE;
				}
				
				function _alert_demo_signup($lang, $user_id){
						$opts = read_options('', 'OBJECT');
						
						$tpl_email = new Tpl_email(); $tpl_email->where('type','signup_demo_conf')->get(1);
						$user = new User(); $user->where('id',(int)$user_id)->get(1);
						
						if($tpl_email->exists() && $user->exists())
						{
								$subject = $this->_map_client_presets($user_id, $tpl_email->subject);
								$subject = $this->_map_option_presets($subject);
								$message = $this->_map_client_presets($user_id, $tpl_email->message);
								$message = $this->_map_option_presets($message);

								$this->load->library('email');
								$config['protocol'] 	= 'smtp';
								$config['smtp_host'] 	= ($opts->smtp_ssl=='yes'&& substr(strtolower($opts->smtp_host), 0, 6)!='ssl://' ? 'ssl://' : '') . $opts->smtp_host;
								$config['smtp_user'] 	= $opts->smtp_user;
								$config['smtp_pass'] 	= $opts->smtp_pass;
								$config['smtp_port'] 	= $opts->smtp_port;
								$config['mailtype'] 	= 'html';
								$config['charset'] 		= 'utf-8';
								$config['wordwrap']  	= TRUE;
								$this->email->initialize($config);
								$this->email->set_newline("\r\n");
								
								$this->email->from($opts->smtp_user, $opts->company_name);
								$this->email->to($user->email);
								$this->email->subject($subject);
								$this->email->message($message);
								$this->email->send();
								$data = $this->email->print_debugger();
								// if($fp = fopen('./demo-email-log-txt', 'wa+'))
								// {
										// fputs($fp, $data);
										// fclose($fp);
								// }
								if(preg_match('#Your message has been successfully sent#is', $data))
								{
										log_activity('Demo Signup e-mail successfully sent to '.$user->email, 'user', 'demo_signup', 'system');
								}
								else
								{
										log_activity('Failure sending Demo Signup e-mail to '.$user->email, 'user', 'demo_signup', 'system');
								}
						}
				}
				
				function register_partner(){
						$lang = $this->_resolve_lang();
						
						$this->lang->load('users_register_partner', $lang);
						$data['ref'] 			= $this->_resolve_referrer();
						$data['base_url'] 		= base_url();
						$localized_errors		= array (
								'error_field_required' => $this->lang->line('error_field_required'),
								'error_password_match' => $this->lang->line('error_password_match'),
						);
						$data['locale'] 							= array('lang'=>$lang, 'errors'=>$localized_errors, 'msg_loading'=>$this->lang->line('msg_loading').'...', 'msg_processing'=>$this->lang->line('label_processing'),'select_choose'=>$this->lang->line('select_choose').'...');
						$data['locale']['label_dob_month']			= $this->lang->line('label_dob_month');
						$data['locale']['label_dob_day']			= $this->lang->line('label_dob_day');
						$data['locale']['label_dob_year']			= $this->lang->line('label_dob_year');
						$data['locale']['months_list']				= $this->lang->line('months_list');
						$data['locale']['securities_exp_list']		= $this->lang->line('securities_exp_list');
						$data['locale']['currencies_exp_list']		= $this->lang->line('currencies_exp_list');
						$data['locale']['futures_exp_list']			= $this->lang->line('futures_exp_list');
						$data['locale']['commodities_exp_list']		= $this->lang->line('commodities_exp_list');
						
						$opts = read_options('company_name', 'OBJECT');
						
						$data['company_name'] = $opts->company_name;
						$this->load->view('users/register_partner', $data);
						
				}
				
				function register_psuccess(){	
						
						$user_id = $this->uri->segment(3);
						if(!$user_id)
						{
								redirect( base_url() . 'users/register_partner/' );
						}
						
						$user = new User();
						$user->where('id',(int)$user_id)->get(1);
						if(!$user->exists())
						{
								redirect( base_url() . 'users/register_partner/' );
						}
						
						$opts = read_options('company_name', 'OBJECT');
						
						$lang = $this->_resolve_lang();
						$this->lang->load('users_register_partner', $lang);
						$data['base_url'] = base_url();
						$data['user'] = $user;
						$data['company_name'] 	= $opts->company_name;
						$this->load->view('users/register_partner_success', $data);
				}
				
				function test_mt4(){
						$this->load->library('mt4');
						$opts = read_options('mt4_host,mt4_port', 'OBJECT');
						
						if(!$this->mt4->connect($opts->mt4_host, $opts->mt4_port))
						{
								die(json_encode(array('stat'=>'error', 'msg'=>$this->mt4->errstr)));
						}
						
						$params = array();
						$params['login'] = '66668126';
						$ret = $this->mt4->request("getaccountinfo", $params);
						if(isset($ret['result']))
						{
								if($ret['result']<0)
								{
										die(json_encode(array('stat'=>'error', 'msg'=>@$ret['reason']?@$ret['reason']:'An unexpected error occurred.')));
								}
								print_r($ret);
								die();
						}
				}
				
				function ajax_register_partner_OLD(){
						$langs	= array('en','fr');
						$lang 	= $this->input->post('lang') && in_array($this->input->post('lang'),$langs) ? $this->input->post('lang') : $langs[0];
						
						if( $this->input->is_ajax_request() ) {
								$this->_validate_partner_signup();
								
								$country_name 	= '';
								$user_title 	= '';
								
								$title = new User_title();
								$title->where('id',(int)$this->input->post('title'))->get(1);
								if($title->exists()) {
										if($title->lang==$langs[0])
										{
												$user_title = $title->title;
										}
										else
										{
												$rel_title = new User_title();
												$rel_title->where('lang',$langs[0])->where('id',$title->rel_id)->get(1);
												if($rel_title->exists()) $user_title = $rel_title->title;
										}
								}
								
								$country = new Country();
								$country->where('id',(int)$this->input->post('country'))->get(1);
								if($country->exists()) {
										if($country->lang==$langs[0])
										{
												$country_name = $country->name_short;
										}
										else
										{
												$rel_country = new Country();
												$rel_country->where('lang',$langs[0])->where('iso_num',$country->iso_num)->get(1);
												if($rel_country->exists()) $country_name = $rel_country->name_short;
										}
								}
								
								$mt4_agent  = '';
								$ref 		= $this->input->post('ref') ? $this->input->post('ref') : $this->_resolve_referrer();
								$referrer 	= new User();
								if($ref>0) 
								{
										$referrer->where('id',(int)$ref)->get(1);
										if($referrer->exists())
										{
												$mt4_agent = $referrer->mt4_uid;
										}
								}
								else
								{
										$user_tree = new User();
										$user_tree->where('email',$this->security->xss_clean($this->input->post('email')))->order_by('id','asc')->get();
										foreach($user_tree as $rel_user)
										{
												if($rel_user->mt4_agent)
												{
														$mt4_agent = $rel_user->mt4_agent;
														break;
												}
										}
								}
								
								// Saving user infos in database
								$this->load->library('encrypt');
								$user = new User();
								$user->lang 				= $lang;
								$user->type 				= 'real';
								$user->title 				= $user_title;
								$user->firstname 			= $this->input->post('firstname');
								$user->lastname 			= $this->input->post('lastname');
								$user->country 				= $country_name;
								$user->email 				= $this->input->post('email');
								$user->password 			= $this->encrypt->encode($this->input->post('password'));
								$user->phone 				= $this->input->post('phone');
								$user->phone2 				= $this->input->post('phone2');
								$user->address1 			= $this->input->post('address1');
								$user->address2 			= $this->input->post('address2');
								$user->city 				= $this->input->post('city');
								$user->state 				= $this->input->post('state');
								$user->citizenship 			= $this->input->post('citizenship');
								$user->nid 					= $this->input->post('nid');
								$user->dob_day 				= $this->input->post('dob_day');
								$user->dob_month 			= $this->input->post('dob_month');
								$user->dob_year 			= $this->input->post('dob_year');
								$user->dob_ts 				= mktime(0,0,0,$user->dob_month,$user->dob_day,$user->dob_year);
								$user->business 			= $this->input->post('business');
								$user->exp_forex 			= $this->input->post('exp_forex');
								$user->customers_monthly 	= $this->input->post('customers_monthly');
								$user->total_accts 			= $this->input->post('total_accts');
								$user->total_clients_funds 	= $this->input->post('total_clients_funds');
								$user->broker_relation 		= $this->input->post('broker_relation');
								
								$cc = '';
								if( is_array($this->input->post('clients_countries')) && count($this->input->post('clients_countries'))>0 )
								{
										$cids 	= $this->input->post('clients_countries');
										$c 		= new Country();
										$rel_c 	= new Country();
										foreach($cids as $cid){
												$c->clear();
												$c->where('id',(int)$cid)->get(1);
												if($c->exists()) {
													if($c->lang==$langs[0]) {
															$cc .= ($cc ? '|' : '').$c->name_short;
													}
													else
													{
															$rel_c->clear();
															$rel_c->where('lang',$langs[0])->where('iso_num',$c->iso_num)->get(1);
															if($rel_c->exists()) $cc .= ($cc ? '|' : '').$rel_c->name_short;
															else 				 $cc .= ($cc ? '|' : '').$c->name_short;
													}
												}
										}
								}
								
								$user->clients_countries = $cc;
								$user->website 			 = $this->input->post('website');
								$user->promo_material 	 = $this->input->post('promo_material');
								$user->promo_method 	 = $this->input->post('promo_method');
								$user->other_info 		 = $this->input->post('other_info');
								
								$tu = new User(); 
								$tu->where('email',$this->security->xss_clean($this->input->post('email')))->get(1);
								
								$user->primary_acct  	= $tu->exists()?'no':'yes';
								$user->first_login  	= 'yes';
								$user->added 			= time();
								$user->user_ip 			= $this->input->ip_address();
								$user->u_stat 			= "pending_partner";
								$user->save();
								$user_id 				= $this->db->insert_id();
								
								// Sending user infos to MT4 server
								$opts = read_options('company_name', 'OBJECT');
								
								$host 		= $opts->mt4_host;
								$port 		= (int)$opts->mt4_port;
								$leverage 	= $opts->default_leverage;	
								$group 		= $opts->default_group;
								$agent 		= $opts->default_agent;
								
								$this->load->library('mt4');
								if($this->mt4->connect($opts->mt4_host, (int)$opts->mt4_port)===FALSE)
								{
										die(json_encode(array('stat'=>'error', 'msg'=>$this->mt4->errstr, 'version'=>'2.0')));
								}
								
								$explicit_referral = $this->_fetch_explicit_referral();
								
								$params 						= array();
								$params['state'] 				= $user->state;
								$params['email'] 				= $user->email;
								$params['group'] 				= $group;
								$params['city'] 				= $user->city;
								$params['password_investor'] 	= '0';
								$params['leverage'] 		 	= 400;
								$params['id'] 					= '';
								$params['address'] 				= $user->address1 . ($user->address2 ? ' ' . $user->address2 : '');
								$params['country'] 				= $country->country;
								$params['password'] 			= $this->input->post('password');
								$params['password_phone'] 		= '';
								$params['name'] 				= $user->firstname . ($user->firstname&&$user->lastname?' ':'') . $user->lastname;
								$params['zipcode'] 				= '';
								$params['phone'] 				= $this->input->post('phone');
								$params['login'] 				= 0;
								$params['comment'] 				= "partner #$user_id";
								$params['agent'] 				= $explicit_referral ? $explicit_referral : ($mt4_agent ? $mt4_agent : $agent);
								
								$answerData = $this->mt4->request("createaccount", $params);
								if($answerData===FALSE)
								{
										die(json_encode(array('stat'=>'error', 'msg'=>$this->mt4->errstr, 'version'=>'2.0')));
								}
								
								if(isset($answerData['result']))
								{
										if($answerData['result']<0)
										{
												die(json_encode(array('stat'=>'error', 'msg'=>@$answerData['reason']?@$answerData['reason']:'An unexpected error occurred.', 'version'=>'2.0')));
										}
										
										$params 		 = array();
										$params['login'] = @$answerData['login'];
										$accountInfo 	 = $this->mt4->request("getaccountinfo", $params);
										
										if(isset($accountInfo['group']))
										{
												$user->clear();
												$user->where('id',$user_id)->update( array('mt4_uid'=>@$answerData['login'], 'mt4_agent'=>@$accountInfo['agent'],'mt4_group'=>$accountInfo['group'],'u_updated'=>time()) );
										}
										
										$this->_alert_admin_partner($lang, $user_id);
										
										die( json_encode(array('stat'=>'success','user_id'=>$user_id, 'version'=>'2.0')) );
								}
						}
				}
				
				function ajax_register_partner(){
						$langs	= array('en','fr');
						$lang 	= $this->input->post('lang') && in_array($this->input->post('lang'),$langs) ? $this->input->post('lang') : $langs[0];
						
						if( $this->input->is_ajax_request() ) {
								$this->_validate_partner_signup();
								
								$country_name 	= '';
								$user_title 	= '';
								$dmp = $this->config->item('datamapper');
								
								$title = new User_title();
								$title->where('id',(int)$this->input->post('title'))->get(1);
								if($title->exists()) {
										if($title->lang==$langs[0])
										{
												$user_title = $title->title;
										}
										else
										{
												$rel_title = new User_title();
												$rel_title->where('lang',$langs[0])->where('id',$title->rel_id)->get(1);
												if($rel_title->exists()) $user_title = $rel_title->title;
										}
								}
								
								$country = new Country();
								$country->where('id',(int)$this->input->post('country'))->get(1);
								if($country->exists()) {
										if($country->lang==$langs[0])
										{
												$country_name = $country->name_short;
										}
										else
										{
												$rel_country = new Country();
												$rel_country->where('lang',$langs[0])->where('iso_num',$country->iso_num)->get(1);
												if($rel_country->exists()) $country_name = $rel_country->name_short;
										}
								}
								
								$mt4_agent  = '';
								$ref 		= $this->input->post('ref') ? $this->input->post('ref') : $this->_resolve_referrer();
								$referrer 	= new User();
								if($ref>0)  {
										$referrer->where('id',(int)$ref)->get(1);
										if($referrer->exists())
										{
												$mt4_agent = $referrer->mt4_uid;
										}
								}
								else
								{
										$user_tree = new User();
										$user_tree->where('email',$this->security->xss_clean($this->input->post('email')))->order_by('id','asc')->get();
										foreach($user_tree as $rel_user)
										{
												if($rel_user->mt4_agent)
												{
														$mt4_agent 		= $rel_user->mt4_agent;
														break;
												}
										}
								}
								
								$this->load->library('encrypt');
								
								$explicit_referral 			= $this->_fetch_explicit_referral();
								
								# Save user info in database
								$tu   = new User();  		$tu->where('email', $this->security->xss_clean($this->input->post('email')))->get(1);
								$user = new User();
								$user->lang 				= $lang;
								$user->type 				= 'real';
								$user->title 				= is_numeric($user_title) ? $this->_fetch_user_title_by_id($user_title) : $user->title;
								$user->firstname 			= $this->input->post('firstname');
								$user->lastname 			= $this->input->post('lastname');
								$user->country 				= is_numeric($country_name) ? $this->_fetch_country_by_id($country_name) : $country_name;
								$user->email 				= $this->input->post('email');
								$user->password 			= $this->encrypt->encode($this->input->post('password'));
								$user->phone 				= $this->input->post('phone');
								$user->phone2 				= $this->input->post('phone2');
								$user->address1 			= $this->input->post('address1');
								$user->address2 			= $this->input->post('address2');
								$user->city 				= $this->input->post('city');
								$user->state 				= $this->input->post('state');
								$user->citizenship 			= $this->input->post('citizenship');
								$user->nid 					= $this->input->post('nid');
								$user->dob_day 				= $this->input->post('dob_day');
								$user->dob_month 			= $this->input->post('dob_month');
								$user->dob_year 			= $this->input->post('dob_year');
								$user->dob_ts 				= mktime(0,0,0,$user->dob_month,$user->dob_day,$user->dob_year);
								$user->business 			= $this->input->post('business');
								$user->exp_forex 			= $this->input->post('exp_forex');
								$user->customers_monthly 	= $this->input->post('customers_monthly');
								$user->total_accts 			= $this->input->post('total_accts');
								$user->total_clients_funds 	= $this->input->post('total_clients_funds');
								$user->broker_relation 		= $this->input->post('broker_relation');
								
								$cc = '';
								if( is_array($this->input->post('clients_countries')) && count($this->input->post('clients_countries'))>0 )
								{
										$cids 	= $this->input->post('clients_countries');
										$c 		= new Country();
										$rel_c 	= new Country();
										foreach($cids as $cid){
												$c->clear();
												$c->where('id',(int)$cid)->get(1);
												if($c->exists()) {
													if($c->lang==$langs[0]) {
															$cc .= ($cc ? '|' : '').$c->name_short;
													}
													else
													{
															$rel_c->clear();
															$rel_c->where('lang',$langs[0])->where('iso_num',$c->iso_num)->get(1);
															if($rel_c->exists()) $cc .= ($cc ? '|' : '').$rel_c->name_short;
															else 				 $cc .= ($cc ? '|' : '').$c->name_short;
													}
												}
										}
								}
								
								$user->clients_countries = $cc;
								$user->website 			 = $this->input->post('website');
								$user->promo_material 	 = $this->input->post('promo_material');
								$user->promo_method 	 = $this->input->post('promo_method');
								$user->other_info 		 = $this->input->post('other_info');
								$user->primary_acct  	 = $tu->exists()?'no':'yes';
								$user->first_login  	 = 'yes';
								$user->referral 		 = $explicit_referral;
								$user->u_added 			 = time();
								$user->user_ip 			 = $this->input->ip_address();
								$user->u_stat 			 = 'active';
								$user->save();
								$user_id 				 = $this->db->insert_id();
								log_activity('Account #' . $user_id . ' (signup): user info successfully saved in database. E-mail: ' . $user->email, 'user', 'partner_signup', 'system');
											
								# prepare request to MT4 server			
								$opts 							= read_options('mt4_host,mt4_port,partner_leverage,partner_group,default_agent', 'OBJECT');								
								$params 						= array();
								$params['state'] 				= $user->state;
								$params['email'] 				= $user->email;
								$params['group'] 				= $opts->partner_group;
								$params['city'] 				= $user->city;
								$params['password_investor'] 	= '0';
								$params['leverage'] 		 	= $opts->partner_leverage;
								$params['id'] 					= '';
								$params['address'] 				= $user->address1 . ($user->address2 ? ' ' . $user->address2 : '');
								$params['country'] 				= $user->country;
								$params['password'] 			= $this->input->post('password');
								$params['password_phone'] 		= '';
								$params['name'] 				= $user->firstname . ($user->firstname&&$user->lastname?' ':'') . $user->lastname;
								$params['zipcode'] 				= '';
								$params['phone'] 				= $this->input->post('phone');
								$params['login'] 				= 0;
								$params['comment'] 				= "partner #$user_id";
								$params['agent'] 				= $explicit_referral && is_numeric($explicit_referral) ? $explicit_referral : ($mt4_agent ? $mt4_agent : $opts->default_agent);
								
								$this->load->library('mt4');
								
								# 5 connection attemps to MT4 server
								$connected = false;
								for($i=0;$i<3;$i++)
								{
										if($this->mt4->connect($opts->mt4_host, (int)$opts->mt4_port)!==FALSE)
										{
												$connected = true;
												break;
										}
										sleep(1);
								}
								if(!$connected) // Connection failed. Rollback...
								{
										if($user_id>0) $this->db->delete(@$dmp['prefix'] . 'users', array('id' => (int)$user_id)); 
										log_activity('Account #' . $user_id . ' (signup): Connection to server failed (Reason: '.$this->mt4->errstr.'). User record removed from database.', 'user', 'partner_signup', 'system');
										die(json_encode(array('error'=>$this->mt4->errstr)));
								}
								
								# 'createaccount' request to MT4 server
								$resp = $this->mt4->request("createaccount", $params);
								if($resp===FALSE) 			
								{
										if($user_id>0) $this->db->delete(@$dmp['prefix'] . 'users', array('id' => (int)$user_id)); 
										log_activity('Account #' . $user_id . ' (signup): MT4 \'createaccount\' request failed (Reason: '.$this->mt4->errstr.'). User record removed from database. Parameters: ' . print_r($params, true), 'user', 'partner_signup', 'system');
										die(json_encode(array('error'=>$this->mt4->errstr)));
								}
								
								if(!isset($resp['result'])) die(json_encode(array('error'=>'Internal Error.')));
								if($resp['result']<0) 		
								{
										if($user_id>0) $this->db->delete(@$dmp['prefix'] . 'users', array('id' => (int)$user_id)); 
										log_activity('Account #' . $user_id . ' (signup): MT4 \'createaccount\' request failed (Reason: '.@$resp['reason'].'). User record removed from database. Parameters: ' . print_r($params, true), 'user', 'partner_signup', 'system');
										print_r($resp);
										die(json_encode(array('error'=>'Error: ' . @$resp['reason'])));
								}
								
								# Update user MT4 ID
								if(@$resp['login']>0)
								{
										$user->clear();
										$user->where('id', $user_id)->update(array('mt4_uid'=>$resp['login'], 'u_updated'=>time()));
										log_activity('Account #' . $user_id . ' (signup): MT4 Account successfully created. MT4 ID: ' . $resp['login'] . '.', 'user', 'partner_signup', 'system');
								}
								
								# Get account info from MT4 server and update agent and group
								$ACK 			 = false;
								$params 		 = array();
								$params['login'] = @$resp['login'];
								for($i=0;$i<3;$i++)
								{
										$accountInfo = $this->mt4->request("getaccountinfo", $params);
										if(isset($accountInfo['group']) && isset($accountInfo['agent']))
										{
												$user->clear();
												$user->where('id', $user_id)->update( array('mt4_group'=>$accountInfo['group'], 'mt4_agent'=>@$accountInfo['agent'], 'u_updated'=>time()) );
												$ACK = true;
												break;
										}
										sleep(1);
								}
								if(!$ACK)
								{
										log_activity('Account #' . $user_id . ' (signup): Could not retrieve MT4 agent and group for this user.', 'user', 'partner_signup', 'system');
								}
								
								$this->_alert_admin_partner($lang, $user_id);
									
								$this->mt4->disconnect();
								log_activity('Account #' . $user_id . ' (signup): Disconnected from MT4 server.', 'user', 'partner_signup', 'system');
								die( json_encode(array('success'=>true, 'user_id'=>$user_id)) );
						}
						die(json_encode(array('error'=>'Malformed request.')));
				}
				
				function _sync_mt4_pwd($login, $pass){
						$this->load->library('mt4');
						$opts = read_options('mt4_host,mt4_port', 'OBJECT');
						if($this->mt4->connect($opts->mt4_host, (int)$opts->mt4_port)===FALSE)
						{
								return false;
						}
						$params['login'] 	 = $login;
						$params['pass']  	 = $pass;
						$params['investor']  = 0;
						$answerData 		 = $this->mt4->request('changepassword', $params);
						if($answerData===FALSE) return false;
						if(isset($answerData['result']))
						{
								if($answerData['result']<0) return false;
								else return true;
						}
						return false;
				}
			
				function _validate_partner_signup(){
						$lang = $this->_resolve_lang();
						$this->lang->load('users_register_partner', $lang);
						$user = new User();
						$user->where('email',$this->input->post('email'))->where('email !=','')->get(1);
						
						if( !$this->input->post('title') ) {
								die( json_encode(array('field_id'=>'title','error'=>$this->lang->line('error_field_required'))) );
						} elseif( !$this->input->post('firstname') ) {
								die( json_encode(array('field_id'=>'firstname','error'=>$this->lang->line('error_field_required'))) );
						} elseif( !$this->input->post('lastname') ) {
								die( json_encode(array('field_id'=>'lastname','error'=>$this->lang->line('error_field_required'))) );
						} elseif( !$this->input->post('country') ) {
								die( json_encode(array('field_id'=>'country','error'=>$this->lang->line('error_field_required'))) );
						} elseif( !$this->input->post('email') ) {
								die( json_encode(array('field_id'=>'email','error'=>$this->lang->line('error_field_required'))) );
						} elseif( !$this->input->post('password') ) {
								die( json_encode(array('field_id'=>'password','error'=>$this->lang->line('error_field_required'))) );
						} elseif( !$this->input->post('phone') ) {
								die( json_encode(array('field_id'=>'phone','error'=>$this->lang->line('error_field_required'))) );
						} elseif( !$this->input->post('address1') ) {
								die( json_encode(array('field_id'=>'firstname','error'=>$this->lang->line('error_field_required'))) );
						} elseif( !$this->input->post('city') ) {
								die( json_encode(array('field_id'=>'city','error'=>$this->lang->line('error_field_required'))) );
						} elseif( !$this->input->post('state') ) {
								die( json_encode(array('field_id'=>'state','error'=>$this->lang->line('error_field_required'))) );
						} elseif( !$this->input->post('citizenship') ) {
								die( json_encode(array('field_id'=>'citizenship','error'=>$this->lang->line('error_field_required'))) );
						} elseif( !$this->input->post('nid') ) {
								die( json_encode(array('field_id'=>'nid','error'=>$this->lang->line('error_field_required'))) );
						} elseif( !$this->input->post('dob_day') ) {
								die( json_encode(array('field_id'=>'dob_day','error'=>$this->lang->line('error_field_required'))) );
						} elseif( !$this->input->post('dob_month') ) {
								die( json_encode(array('field_id'=>'dob_month','error'=>$this->lang->line('error_field_required'))) );
						} elseif( !$this->input->post('dob_year') ) {
								die( json_encode(array('field_id'=>'dob_year','error'=>$this->lang->line('error_field_required'))) );
						}
						
						return TRUE;
				}
		
				function _alert_partner_signup($lang,$user_id,$password){
						$opts = read_options('', 'OBJECT');
						
						$tpl_email = new Tpl_email(); $tpl_email->where('type','signup_partner_conf')->get(1);
						$user = new User(); $user->where('id',(int)$user_id)->get(1);
						
						if($tpl_email->exists() && $user->exists())
						{
								$subject = $this->_map_client_presets($user_id, $tpl_email->subject);
								$subject = $this->_map_option_presets($subject);
								$message = $this->_map_client_presets($user_id, $tpl_email->message);
								$message = $this->_map_option_presets($message);

								$this->load->library('email');
								$config['protocol'] 	= 'smtp';
								$config['smtp_host'] 	= ($opts->smtp_ssl=='yes'&& substr(strtolower($opts->smtp_host), 0, 6)!='ssl://' ? 'ssl://' : '') . $opts->smtp_host;
								$config['smtp_user'] 	= $opts->smtp_user;
								$config['smtp_pass'] 	= $opts->smtp_pass;
								$config['smtp_port'] 	= $opts->smtp_port;
								$config['mailtype'] 	= 'html';
								$config['charset'] 		= 'utf-8';
								$config['wordwrap']  	= TRUE;
								$this->email->initialize($config);
								$this->email->set_newline("\r\n");
								
								$this->email->from($opts->smtp_user, $opts->company_name);
								$this->email->to($user->email);
								$this->email->subject($subject);
								$this->email->message($message);
								$this->email->send();
								$data = $this->email->print_debugger();
								if($fp = fopen('./partner-email-log-txt', 'wa+'))
								{
										fputs($fp, $data);
										fclose($fp);
								}
						}
				}
				
				function _alert_admin_partner($lang, $user_id) {
						$opts = read_options('', 'OBJECT');
						
						$user = new User(); 
						$user->where('id',(int)$user_id)->get(1);
						
						if($user->exists())
						{
								$this->load->library('encrypt');
								
								$subject = $user->firstname.($user->firstname&&$user->lastname?' ':'').$user->lastname.' #'.$user->mt4_uid.' has just signed up for Partners, Awaiting Approval.';
								$message = "
Pending Partner Informations:
---
Title: 					".$user->title."
First Name: 			".$user->firstname."
Last Name: 				".$user->lastname."
Country: 				".$user->country_name."
E-mail: 				".$user->email."
Password: 				".$this->encrypt->decode($user->password)."
Phone: 					".$user->phone."
Phone2: 				".$user->phone2."
Address line 1: 		".$user->address1."
Address line 2:			".$user->address2."
City: 					".$user->city."
State: 					".$user->state."
Citizenship: 			".$user->citizenship."
Passport ID: 			".$user->nid."
Date of birth: 			".$user->dob_month."/".$user->dob_day."/".$user->dob_year."
Business: 				".$user->business."
Experience in forex: 	".$user->exp_forex."
Monthly customers:		".$user->customers_monthly."
Total accounts: 		".$user->total_accts."
Total clients' funds: 	".$user->total_clients_funds."
Broker relation: 		".$user->broker_relation."
Website: 				".$user->website."
Promo_material: 	 	".$user->promo_material."
Promo_method: 	 		".$user->promo_method."
Other_info: 		 	".$user->other_info."

IP Address: 			".$this->input->ip_address()."
---
";

								$this->load->library('email');
								$config['protocol'] 	= 'smtp';
								$config['smtp_host'] 	= ($opts->smtp_ssl=='yes'&& substr(strtolower($opts->smtp_host), 0, 6)!='ssl://' ? 'ssl://' : '') . $opts->smtp_host;
								$config['smtp_user'] 	= $opts->smtp_user;
								$config['smtp_pass'] 	= $opts->smtp_pass;
								$config['smtp_port'] 	= $opts->smtp_port;
								$config['mailtype'] 	= 'html';
								$config['charset'] 		= 'utf-8';
								$config['wordwrap']  	= TRUE;
								$this->email->initialize($config);
								$this->email->set_newline("\r\n");
								
								$this->email->from($opts->smtp_user, $opts->company_name);
								$this->email->to($opts->admin_email);
								$this->email->subject($subject);
								$this->email->message(nl2br($message));
								$this->email->send();
								$data = $this->email->print_debugger();
								// if($fp = fopen('./admin-partner-email-log-txt', 'wa+'))
								// {
										// $data .= "\n\nsmtp_host=" . $config['smtp_host'];
										// $data .= "\nsmtp_user="   . $config['smtp_user'];
										// $data .= "\nsmtp_pass="   . $config['smtp_pass'];
										// fputs($fp, $data);
										// fclose($fp);
								// }
								if(preg_match('#Your message has been successfully sent#is', $data))
								{
										log_activity('Partner Signup notice successfully sent to '.$opts->admin_email, 'user', 'partner_signup', 'system');
								}
								else
								{
										log_activity('Failure sending Partner Signup notice to '.$opts->admin_email, 'user', 'partner_signup', 'system');
								}
						}
				}
				
				function _fetch_country_by_id($id) {
						if($id>0)
						{
								$country = new Country();
								$country->where('id', (int)$id)->get(1);
								if($country->exists()) return $country->name_short;
						}
				}
				
				function _fetch_user_title_by_id($id) {
						if($id>0)
						{
								$title = new User_title();
								$title->where('id',(int)$id)->where('lang','en')->get(1);
								if($title->exists()) return $title->title;
						}
				}
				
		}

/* End of file users.php */
/* Location: ./system/application/controller/user.php */